import sys
import time
import traceback

from PyQt6.QtWidgets import (
    QApplication, QDialog, QProgressBar, QVBoxLayout, QPushButton, QMessageBox
)
from PyQt6.QtCore import QThread, pyqtSignal, Qt


class Worker(QThread):
    """子线程，用于执行耗时任务"""
    progress_updated = pyqtSignal(int)  # 进度更新信号
    task_finished = pyqtSignal()  # 任务完成信号
    error_occurred = pyqtSignal(str)  # 错误信号，传递错误信息

    def __init__(self, func):
        super().__init__()
        self.func = func

    def run(self):
        try:
            flag = self.func()

            print(flag)
            if flag:
                self.task_finished.emit()
            elif flag is False:
                self.error_occurred.emit("请检查输入内容是否为空！")
        except Exception as e:
            # 捕获异常并发送错误信号
            error_msg = traceback.format_exc()  # 获取完整的错误信息
            self.error_occurred.emit(error_msg)


class ProgressDialog(QDialog):
    """置顶的进度条对话框"""
    def __init__(self, func):
        super().__init__()
        self.setWindowTitle("任务进度")
        self.setGeometry(800, 500, 300, 100)
        self.setWindowFlags(self.windowFlags() |
                            Qt.WindowType.WindowStaysOnTopHint)  # 设置窗口置顶

        # 创建布局和组件
        layout = QVBoxLayout()
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 0)
        layout.addWidget(self.progress_bar)
        self.setLayout(layout)

        # 初始化子线程
        self.worker = Worker(func)
        self.worker.progress_updated.connect(self.update_progress)
        self.worker.task_finished.connect(self.task_completed)
        self.worker.error_occurred.connect(self.task_error)

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)

    def task_completed(self):
        """任务完成"""
        self.close()  # 关闭对话框
        QMessageBox.information(self, "完成", "任务已完成！")

    def task_error(self, error_msg):
        # 显示错误信息
        QMessageBox.critical(self, "错误", f"任务出错：\n{error_msg}")
        self.close()


class MainWindow(QDialog):
    """主窗口"""
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        self.setGeometry(100, 100, 300, 200)

        # 创建布局和组件
        layout = QVBoxLayout()
        self.button = QPushButton("开始任务", self)
        self.button.clicked.connect(self.show_progress_dialog)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def show_progress_dialog(self):
        """显示进度条对话框并启动任务"""
        self.progress_dialog = ProgressDialog()
        self.progress_dialog.worker.start()  # 启动子线程
        self.progress_dialog.exec()  # 显示对话框（模态）


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())